package com.captain.leetcode2.链表;

import com.captain.leetcode.链表.ListNode;

import java.util.Objects;

public class 两数相加02 {

    public static void main(String[] args) {
        ListNode l1 = ListNode.getInstance();
        ListNode l2 = ListNode.getInstance1();
        ListNode listNode = new 两数相加02().addTwoNumbers(l1, l2);
        System.out.println(listNode);
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;

        //记录进位
        int n = 0;
        ListNode dummy = new ListNode(-1);
        ListNode pre = dummy;
        while (l1 != null && l2 != null) {
            int v1 = l1.val;
            int v2 = l2.val;
            int sum = v1 + v2 + n;
            int val = sum % 10;
            pre.next = new ListNode(val);
            n = sum / 10;
            pre = pre.next;
            l1 = l1.next;
            l2 = l2.next;
        }
        //l1不为null
        if (l1 != null) {
            while (l1 != null) {
                int sum = l1.val + n;
                int val = sum % 10;
                pre.next = new ListNode(val);
                l1 = l1.next;
                pre = pre.next;
                n = sum / 10;
            }
        }
        if (l2 != null) {
            while (l2 != null) {
                int sum = l2.val + n;
                int val = sum % 10;
                pre.next = new ListNode(val);
                l2 = l2.next;
                pre = pre.next;
                n = sum / 10;
            }
        }
        if (n == 1) {
            pre.next = new ListNode(n);
            return dummy.next;
        }
        return dummy.next;
    }
}
